<?php
/**
 * Created by PhpStorm.
 * User: iyahe@qq.com (天明)
 * Date: 2017/12/8
 * Time: 13:41
 */
namespace app\api\model;
use think\Db;
use think\Model;

/** 金币操作表
 * Class MoneyModel
 * @package app\api\model
 */
class MoneyModel extends Model{
    private static $_instance;
    public static function make() {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * @param     $uid
     * @param     $type
     * @param int $make
     * @return float|int
     */
    public function getMoney($uid,$type,$make=1){
        $where = [
            'money_uid'=>$uid,
            'money_type'=>$type,
            'money_make'=>$make,
            'money_status'=>1
        ];
        $all = Db::name('money')
            ->where($where)->sum('money_number');
        $where['money_make'] = ['<=','0'];
        $jals = Db::name('money')
            ->where($where)->sum('money_number');
        return $all-$jals;
    }

    /**
     * @param        $type 金币类型
     * @param        $money 多少钱
     * @param        $uid 给谁
     * @param int    $make 0 扣除 1增加 -1冻结
     * @param string $note 笔记
     * @param        $money_guid 扣钱id
     * @return int|string
     */
    public function addMoney($type,$money,$uid,$make=1,$note='',$money_guid=''){
        $insert = [];
        $insert['money_type'] = $type;
        $insert['money_addtime'] = getStrtime();
        $insert['money_number'] = $money;
        $insert['money_make'] = $make;
        $insert['money_uid'] = $uid;
        $insert['money_note'] = $note;
        $insert['money_guid'] = $money_guid;
        $count = $this->getMoney($uid,$type);
        if($make <= 0){
            //扣钱, 如果钱不够,返回-1
            if($count-$money > 0){
                return Db::name('money')->insertGetId($insert);
            }else{
                return -1;
            }
        }else{
            //增加钱则直接加
            return Db::name('money')->insertGetId($insert);
        }
    }
    public function getMoneyHis($where,$limit=12){
       return Db::name('money')->where($where)->order('	money_addtime DESC')->paginate($limit);
    }

    /**
     * @param $uid 我的uid
     * @param $you 对方uid
     * @param $uuid 扣除的索引
     * @return bool
     */
    public function changeAccounts($uid,$you,$uuid){
        //扣除当前用户的钱
        Db::startTrans();//启动事务
        $where = ['money_guid'=>$uuid,'money_uid'=>$uid];
        $number = Db::name('money')->where($where)->field('money_number')->find();
        $money =  Db::name('money')->where($where)->update(['money_make'=>0]);
        if($money){
            $result = $this->addMoney(2,$number['money_number'],$you,1,'接单收入');
            if($result){
                Db::commit();
                return true;
            }
        }
        Db::rollback();
        return false;
    }
}